package com.netty.cn.model.websocket.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

/**
 * 
 * @author wangzonghui
 * @date 2021-08-06 11:11:14
 * @Description websocket chandler
 */
public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
 
    private final String HEART = "ws-heart";
 
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {
        String text = textWebSocketFrame.text();
        System.out.println("接收到消息: " + text);
        // 判断接收内容是否为心跳值
        if(HEART.equals(text)){
            TextWebSocketFrame socketFrame = new TextWebSocketFrame(HEART);
            channelHandlerContext.writeAndFlush(socketFrame);
        }
    }
 
    /**
     * 用户连接
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        super.channelRegistered(ctx);
        System.out.println("用户连接");
    }
 
    /**
     * 用户断开
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        super.channelUnregistered(ctx);
        System.out.println("用户断开");
    }
 
    /**
     * 用户退出状态提示
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        System.out.println("用户非正常断开");
    }

}
